package com.skeleton.common.interceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.LogManager;
import org.apache.log4j.Logger;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import com.skeleton.db.dto.UserinfoDto;
import com.skeleton.utils.BaseConstants;

@Component
public class SystemInterceptor extends HandlerInterceptorAdapter {

	protected Logger logger = LogManager.getLogger(this.getClass());

	String[] urls = { 
		"/index", "/guide/ajaxLoadHotGuide", "/user/ajaxLogin", "/user/ajaxRegist", "/resource"
	};

	String[] urls2 = { 
		"/resource", "/admin/adminLogin", "/admin/user/adminAjaxLogin"
	};

	@Override
	public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
		// 当前请求路径
		String currentURI = request.getRequestURI().replace(request.getContextPath(), "").trim();
		// 不需要登陆的url

//		logger.info("================================");
//		logger.info("访问路径：" + currentURI);
//		logger.info("================================");
		logger.debug("================================");
		logger.debug("访问路径：" + currentURI);
		logger.debug("================================");
		
		
		if (currentURI.startsWith("/admin/")) {
			boolean isAllow = false;
			for (int i = 0; i < urls2.length; i++) {
				String url = urls2[i];
				if (currentURI.startsWith(url)) {
					isAllow = true;
				}
			}
			if (!isAllow) {
				UserinfoDto ud = (UserinfoDto) request.getSession().getAttribute(BaseConstants.LOGINUSER_SESSION_NAME_ADMIN);
				if (ud == null) {
					response.sendRedirect("/SkeToolWeb/admin/adminLogin");
					return false;
				} else {
					return super.preHandle(request, response, handler);
				}
			}
		} else {
			boolean isAllow = false;
			for (int i = 0; i < urls.length; i++) {
				String url = urls[i];
				if (currentURI.startsWith(url)) {
					isAllow = true;
				}
			}
			if (!isAllow) {
				UserinfoDto ud = (UserinfoDto) request.getSession().getAttribute(BaseConstants.LOGINUSER_SESSION_NAME);
				if (ud == null) {
					response.sendRedirect("/SkeToolWeb/index");
					return false;
				} else {
					return super.preHandle(request, response, handler);
				}
			}
		}

		return super.preHandle(request, response, handler);
	}

}
